package com.shop.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shop.MongoDB.MongoService;
import com.shop.Redis.GoodsKey;
import com.shop.Redis.OrderKey;
import com.shop.Redis.RedisService;
import com.shop.dao.GoodsOrderInfoMapper;
import com.shop.pojo.Cart;
import com.shop.pojo.Goods;
import com.shop.pojo.GoodsOrderInfo;
import com.shop.pojo.User;
import com.shop.result.JsonResult;
import com.shop.result.PayJsonResult;
import com.shop.service.CartService;
import com.shop.service.LoginService;
import com.shop.util.BaseUtil;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisService redisService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private LoginService loginService;

    @Autowired
    private AliPayServiceImpl aliPayServiceImpl;

    /*定义集合名称*/
    private static final String collectionName = "cart";

    /*获取用户购物车信息*/
    @Override
    public List<Cart> getGoodsCartByToken(String token){
        User user = loginService.getUserByToken(token);
        List<Cart> cartList = new ArrayList<>();

        /*redis做缓存*/
//        Map<String, String> cartMap = redisService.hGetAll(user.getUserId());
//
//        //遍历Map数据，把其中的数据转化为实体类，并添加到List中
//        for (Map.Entry<String, String> map : cartMap.entrySet()) {
//            cartList.add(JSON.toJavaObject(JSON.parseObject(map.getValue().toString()), Cart.class));
//        }

        /*MongoDB做缓存*/
        //定义MongoDB的查询类
        Query query = new Query();  //定义MongoDB的查询表达式对象
        query.fields().include(collectionName); //包含该字段
        query.fields().exclude("_id");  //不包含该字段
        query.addCriteria(Criteria.where("userId").is(user.getUserId()));

        //调用MongoDB的Java操作类
        Object a = mongoTemplate.find(query,Object.class,collectionName);

        //把数据转换成json数组
        JSONArray jsonArray = JSONArray.fromObject(a);
        for (int i = 0, l = jsonArray.size(); i < l; i++) { //遍历json数组，获取其中的json数据
            Map<String,Object> jsonMap =  BaseUtil.json2Map(jsonArray.get(i).toString());   //把json
            String json = BaseUtil.toJson(jsonMap.get(collectionName).toString());

            //把数据转化为实体类
            Cart cart = JSONObject.parseObject(json, Cart.class);

            //把实体数据添加到List列表中
            cartList.add(cart);
        }

        return cartList;
    }

    /*添加商品到用户购物车中*/
    @Override
    public String addGoodToCartByToken(String data, String token) throws Exception {
        data = BaseUtil.dataTranscoding(data);

        String json = BaseUtil.toJson(data);
        Cart cart = JSONObject.parseObject(json, Cart.class);
        User user = loginService.getUserByToken(token);
        if(user == null){
            return "查询失败！该用户已失效，请重新登录";
        }

        //检测商品ID和属性ID是否存在
        if(StringUtils.isBlank(cart.getGoodsId())){
            return "商品不存在，请重新添加";
        }

        if(StringUtils.isBlank(cart.getAttrValsId())){
            return "所选的商品规格有误，请重新选择";
        }

        /*先查询当前用户购物车，是否存在同规格的商品*/
        String goodsKey = cart.getGoodsId()+"-"+cart.getAttrValsId();  //商品key

        /*redis操作*/
//        boolean isCartList = redisService.hasKey(user.getUserId(),null);  //判断购物车是否存在
//        boolean isGoodExist = redisService.hasKey(user.getUserId(),goodsKey); //判断商品是否已存在于用户的购物车中
//
//        if(isCartList && isGoodExist){ //存在则把同规格商品数量加1
//                Cart goods = redisService.getKey(user.getUserId(),goodsKey,Cart.class);
//                cart.setGoodsNum(goods.getGoodsNum()+cart.getGoodsNum());
//        }
//
//        redisService.put(user.getUserId(),goodsKey,cart);   //更新redis中用户购物车信息

        /*MongoDB进行新增或更新操作*/
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(user.getUserId()));
        query.addCriteria(Criteria.where("goodsKey").is(goodsKey));
        query.fields().include(collectionName); //只显示购物车信息
        query.fields().exclude("_id");  //不显示MongoDB数据库中生成的id值
        Map<String,Object> map = mongoTemplate.findOne(query, Map.class, collectionName);   //查询MongoDB中单条的购物车商品数据

        Update update = new Update();
        if(map != null){    //购物车中商品不为空，则需把商品数量加一后进行更新
            String cartJson = BaseUtil.toJson(map.get(collectionName));
            Cart isCart = JSONObject.parseObject(cartJson, Cart.class);
            if(isCart != null){
                isCart.setGoodsNum(isCart.getGoodsNum()+cart.getGoodsNum());
                update.set("cart", isCart);
            }

        }else{  //购物车中商品为空,直接添加商品信息即可
            update.set("cart", cart);
        }

        mongoTemplate.upsert(query,update, Cart.class); //调用MongoDB的Java操作接口，进行新增或更新操作

        return "success";
    }

    /*删除购物车中单个商品*/
    @Override
    public String deleteGoodToCartByToken(String data, String token) throws Exception {
        data = BaseUtil.dataTranscoding(data);
        String json = BaseUtil.toJson(data);
        Cart cart = JSONObject.parseObject(json, Cart.class);
        User user = loginService.getUserByToken(token);

        String goodsKey = cart.getGoodsId()+"-"+cart.getAttrValsId();

        /*redis操作*/
//        Cart redisGoods = redisService.getKey(user.getUserId(),goodsKey,Cart.class);
//        if(null != redisGoods){
//            redisService.deleteKey(user.getUserId(),goodsKey);
//            return "success";
//        }

        /*MongoDB操作*/
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(user.getUserId()));
        query.addCriteria(Criteria.where("goodsKey").is(goodsKey));

        Cart MongoGoods = mongoTemplate.findOne(query,Cart.class);  //查询MongoDB数据中的单条购物车商品数据
        if (MongoGoods != null){    //当查询出来的数据不为空时，方可执行remove方法
            mongoTemplate.remove(query, Cart.class);
            return "success";
        }


        return "该商品不存在于购物车，请重新刷新再试";
    }

    /*清空购物车*/
    @Override
    public String deleteAllGoodToCartByToken(String token) throws Exception {
        User user = loginService.getUserByToken(token);
        if(null == user){
            return "清空失败：用户已失效，请重新登录后再试";
        }

        /*Redis操作*/
//        Map<String, String> cartMap = redisService.hGetAll(user.getUserId());
//        if(null != cartMap){
//            for (Map.Entry<String, String> map : cartMap.entrySet()) {
//                Cart cart = JSONObject.parseObject(map.getValue().toString(), Cart.class);
//                String goodsKey = cart.getGoodsId()+"-"+cart.getAttrValsId();
//                redisService.deleteKey(user.getUserId(),goodsKey);
//            }
//
//            return "success";
//
//        }else{
//            return "清空失败：用户购物车中并不存在商品信息，请刷新页面后再试";
//        }

        /*MongoDB操作*/
        Query query = new Query();
        query.fields().include(collectionName);
        query.fields().exclude("_id");
        query.addCriteria(Criteria.where("userId").is(user.getUserId()));
        Object a = mongoTemplate.find(query,Object.class,collectionName);   //先查询出该用户购物车的商品数据
        JSONArray jsonArray = JSONArray.fromObject(a);

        if(null != jsonArray && jsonArray.size() > 0){
            //遍历商品数据，逐个删除
            for (int i = 0, l = jsonArray.size(); i < l; i++) {
                Map<String,Object> jsonMap =  BaseUtil.json2Map(jsonArray.get(i).toString());
                String json = BaseUtil.toJson(jsonMap.get(collectionName).toString());

                //把数据转化为实体类
                Cart cart = JSONObject.parseObject(json, Cart.class);
                String goodsKey = cart.getGoodsId()+"-"+cart.getAttrValsId();

                //定义好删除条件
                Query goodsQuery = new Query();
                goodsQuery.addCriteria(Criteria.where("userId").is(user.getUserId()));
                goodsQuery.addCriteria(Criteria.where("goodsKey").is(goodsKey));
                mongoTemplate.remove(goodsQuery, Cart.class);   //根据删除条件，执行remove方法
            }

            return "success";

        }else{
            return "清空失败：用户购物车中并不存在商品信息，请刷新页面后再试";
        }

    }

    /*提交购物车*/
    @Override
    public String commitUserCartToPay(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String data = request.getParameter("data");
        String token = request.getParameter("token");

        //先验证用户信息
        User user = loginService.getUserByToken(token);
        if(null == user){
            return "提交失败：用户已失效，请重新登录";
        }

        JSONArray jsonArray = JSONArray.fromObject(data);
        String orderIds = "";
        double totalMoney = 0.00;

        //遍历购物车商品信息
        for (int i = 0, l = jsonArray.size(); i < l; i++) {
            String json = BaseUtil.toJson(jsonArray.get(i));
            Cart cart = JSONObject.parseObject(json, Cart.class);

            /*生成对应的商品订单实体数据*/
            String orderId = BaseUtil.getSID();
            GoodsOrderInfo goodsOrderInfo = new GoodsOrderInfo();
            goodsOrderInfo.setOrderId(orderId);
            goodsOrderInfo.setUserId(user.getUserId());
            goodsOrderInfo.setGoodsId(cart.getGoodsId());
            goodsOrderInfo.setAddrValsId(cart.getAttrValsId());
            goodsOrderInfo.setGoodsName(cart.getGoodsName());
            goodsOrderInfo.setGoodsName(cart.getGoodsName());
            goodsOrderInfo.setGoodsNum(cart.getGoodsNum());
            goodsOrderInfo.setGoodsPrice(cart.getGoodsPrice());
            goodsOrderInfo.setOrderChannel((byte)1);
            goodsOrderInfo.setStatus((byte)0);
            goodsOrderInfo.setCreateDate(new Date());

            /*放入redis中作缓存*/
//            redisService.put(OrderKey.getOrder+user.getUserId(),orderId,goodsOrderInfo);

            /*放入MongoDB数据库中作为缓存*/
            Query query = new Query();
            query.addCriteria(Criteria.where("orderId").is(orderId));

            Update update = new Update();
            update.set("goodsOrder", goodsOrderInfo);
            mongoTemplate.upsert(query,update, GoodsOrderInfo.class,"goodsOrder");

            //把生成的订单号拼接
            orderIds += orderId+",";

            //统计总支付金额
            totalMoney += cart.getGoodsPrice();
        }

        //redis设置订单过期时间，默认15分钟
        redisService.setKeyExpire(OrderKey.getOrder+user.getUserId(),OrderKey.ORDER_EXPIRE);

        //此处调用支付宝的支付接口，并返回支付页面给前端进行支付
        Map<String,Object> params = new HashMap<>();
        params.put("merchantUserId",user.getUserId());
        params.put("merchantUserName",user.getUserName());
        params.put("merchantOrderId",orderIds);
        params.put("totalMoney",String.valueOf(totalMoney));

        PayJsonResult payData = aliPayServiceImpl.goAlipay(params);
        String formData = payData.getData().toString();
//        String formData = "success";

        return formData;
    }

}
